# Copyright (c) 2007 Fabio Makoto Akita
# 
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
# 
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
# 
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

# Author: AkitaOnRails (www.akitaonrails.com)
# Support: Surgeworks LLC (www.surgeworks.com)

# Spawns a separated process to run the software upgrade procedure. 
# everything goes logged and this log is accessed through an Ajax call
class Upgrade
  include SyncsHelper::Processes

  def initialize
    delete_log SyncsHelper::UpgradeRunner.log_file
    
    processor, platform, *rest = RUBY_PLATFORM.split("-")
    if platform != 'mswin32'
      @cmd_cleanup = 'svn cleanup'
      @cmd_svn_up = "svn update --non-interactive"
      @cmd_rake_migrate = "rake db:migrate --trace"
    else      
      @cmd_cleanup = "#{SyncsHelper::WIN_SVN_PATH} cleanup"
      @cmd_svn_up = "#{SyncsHelper::WIN_SVN_PATH} update --non-interactive --username #{$SYNC_CONFIG[:win_svn_username]} --password #{$SYNC_CONFIG[:win_svn_password]}"
      @cmd_rake_migrate = "#{SyncsHelper::WIN_RUBY_PATH} #{SyncsHelper::WIN_RAKE_PATH} db:migrate --trace"
    end
  end
  
  def run    
    File.open(SyncsHelper::UpgradeRunner.log_file, 'a') do |f|
      start_time = Time.now
      f.puts "#{log_timestamp} --- STARTING UPGRADE"
      f.flush
      run_process @cmd_cleanup

      f.puts "#{log_timestamp} --- DOWNLOADING UPGRADES"
      f.flush
      run_process @cmd_svn_up 

      f.puts "#{log_timestamp} --- UPGRADING DATABASE"
      f.flush
      run_process @cmd_rake_migrate

      end_time = Time.now
      f.puts "#{log_timestamp} --- FINISHED UPGRADING. TOTAL TIME: #{log_fmt_timestamp(end_time - start_time)} HOURS."
      f.flush
    end
    exit!
  end
end

Upgrade.new.run